<?php


/**
 * Greendizer invoice controller
 *
 * @author      Youssef El Bied <youssef@greendizer.com>
 */
class Greendizer_Module_InvoiceController extends Mage_Adminhtml_Controller_Sales_Invoice
{
    public function indexAction()
    {
        if ($invoiceId = $this->getRequest()->getParam('id'))
        {
            $invoice = Mage::getModel('sales/order_invoice')->getCollection()->addAttributeToSelect('*')->getItemById($invoiceId);
            try
            {
                set_include_path(sprintf("%s%s%s%slib%sgreendizer-php%sLibrary",
                    get_include_path(),
                    PATH_SEPARATOR,
                    Mage::getModuleDir('', 'Greendizer_Module'),
                    DIRECTORY_SEPARATOR,
                    DIRECTORY_SEPARATOR,
                    DIRECTORY_SEPARATOR
                ));

                require_once 'Greendizer/SellerClient.php';

                $client = new Greendizer_SellerClient(
                    array(
                        'email'		=> Mage::getStoreConfig('greendizer_configuration/authentication/email'),
                        'password'	=> Mage::getStoreConfig('greendizer_configuration/authentication/password')
                    )
                );
                $collection = $client->getUser()->emails()->getById(Mage::getStoreConfig('greendizer_configuration/authentication/email'))->invoices()->search('customId=='.$invoice->getIncrementId());
                foreach ($collection->getResources() as $resource)
                {
                    $this->_redirectUrl('https://viewer.greendizer.com/#'.$resource->getSecretKey());
                    return;
                }
                throw new Exception(sprintf("%s: unknown custom id for a Greendizer invoice.", $invoice->getIncrementId()));
            }
            catch (Exception $e)
            {
                Mage::log(sprintf("%s: could not be loaded from Greendizer.", $invoice->getIncrementId()), Zend_Log::WARN);
                Mage::log($e->getMessage(), Zend_Log::DEBUG);

                $this->_forward('noRoute');
            }
        }
        else
        {
            $this->_forward('noRoute');
        }
    }
}
